package com.hack.validator;

import com.hack.validator.exceptions.ValidationException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ValidationInterceptor {
    private final ValidationEngine validationEngine;

    @Autowired
    public ValidationInterceptor(ValidationEngine validationEngine) {
        this.validationEngine = validationEngine;
    }

    @Before("within(@org.springframework.web.bind.annotation.RestController *) && args(.., @org.springframework.web.bind.annotation.RequestBody *)")
    public void validateRequestBody(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();

        for (Object arg : args) {
            if (arg != null) {
                ValidationResult result = validationEngine.validate(arg);
                if (!result.isValid()) {
                    throw new ValidationException(result);
                }
            }
        }
    }
}